<?php


namespace app\partneradmin\controller;


use app\partneradmin\model\Admin;
use app\partneradmin\model\CustomerServicePersonnel;
use app\partneradmin\model\Partner;
use app\common\controller\partneradmin\Base;
use app\partneradmin\model\PartnerAdminOperationLog;
use super\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Partneradmin extends Base
{
    protected $noNeedLogin = [];

    protected $model;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\partneradmin\model\PartnerAdmin();
    }

    public function index()
    {
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $username = $this->request->post('username', '');
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $rule = $this->request->post('rule', '');
            $partnerId = $this->admin['partner_id'];
            $where['partner_id'] = $partnerId;

            if ($username != '') {
                $where['username'] = ['like', '%' . $username . '%'];
            }
            if ($rule != '') {
                $where['rule'] = $rule;
                if ($rule == 2) {
                    $where['pid'] = $this->admin['id'];
                }
            }
            $field = [
                'id',
                'username',
                'avatar',
                'logintime',
                'loginip',
                'partner_id',
                'create_time',
                'update_time',
                'status',
                'pid',
                'rule',
                'is_bind_google',
                'admin_id',
            ];
            //设置搜索条件
            $where['is_del'] = 0;

            $list = $this->model
                ->with('Partner')
                ->field(implode(',', $field))
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select()
                ->toArray();
            $total = $this->model->where($where)->count('id');
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'list' => $list,
                'totalPage' => $totalPage
            ];
            $this->success('列表', '', $data);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.add';
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    $params['admin_id'] = $this->admin['id'];
                    $partnerInfo = Partner::get($params['partner_id']);
                    if (!$partnerInfo) {
                        $this->error('不存在的合作方数据');
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('不存在的数据');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.edit';
                        $row->validateFailException(true)->validate($validate);
                    }

                    if ($params['password'] != '') {
                        $params['password'] = md5(md5($params['password']) . $row->salt);
                    } else {
                        unset($params['password']);
                    }
                    if ($params['username'] != $row->username) {
                        $username = $this->model->where(['username' => $params['username']])->count('id');
                        if ($username) {
                            throw new Exception('账户名:' . $params['username'] . ' 已被使用！');
                        }
                    }
                    $params['admin_id'] = $this->admin['id'];
                    $partnerInfo = Partner::get($params['partner_id']);
                    if (!$partnerInfo) {
                        $this->error('不存在的合作方数据');
                    }
                    $result = $row->allowField(true)->isUpdate(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('修改成功');
                } else {
                    $this->error('修改失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 日志上报
     */
    public function adminOperationLog()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                if (empty($params['url'])) {
                    $this->error('url参数不能为空！');
                }
                $personnelInfo = [];
                if ($this->admin['rule'] != 3) {
                    $infoWhere = [
                        'partner_admin_id' => $this->admin['id'],
                        'partner_id' => $this->admin['partner_id']
                    ];
                    $personnelInfo = CustomerServicePersonnel::where($infoWhere)->find();
                    if (!empty($personnelInfo)) {
                        //查找合作方
                        $partnerInfo = Partner::get($personnelInfo['partner_id']);
                        $groupInfo = Partner::get($personnelInfo['customer_service_group_id']);
                        $personnelInfo['partner_name'] = $partnerInfo['name'];
                        $personnelInfo['group_name'] = $groupInfo['name'];
                    }
                }
                $setData = [
                    'partner_admin_id' => $this->admin['id'],
                    'url' => $params['url'],
                    'title' => empty($params['title']) ? '' : $params['title'],
                    'send_json' => empty($params['send_json']) ? '{}' : $params['send_json'],
                    'result_json' => empty($params['result_json']) ? '{}' : $params['result_json'],
                    'ip' => request()->ip(),
                    'personnel_name' => empty($personnelInfo) ? '' : $personnelInfo['name'],
                    'partner_name' => empty($personnelInfo) ? '' : $personnelInfo['partner_name'],
                    'group_name' => empty($personnelInfo) ? '' : $personnelInfo['group_name'],
                    'customer_service_group_id' => empty($personnelInfo) ? 0 : $personnelInfo['customer_service_group_id'],
                    'customer_service_personnel_id' => empty($personnelInfo) ? 0 : $personnelInfo['id'],
                    'partner_id' => empty($personnelInfo) ? 0 : $personnelInfo['partner_id'],
                ];
                PartnerAdminOperationLog::create($setData);
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 修改密码
     */
    public function editPassword()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                if (empty($params['password'])) {
                    $this->error('密码不能为空！');
                }
                $info = \app\partneradmin\model\PartnerAdmin::get($this->admin['id']);
                $info->password = md5(md5($params['password']) . $info['salt']);
                $result = $info->save();
                if ($result !== false) {
                    $this->success('修改成功');
                } else {
                    $this->error('修改失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

}